from none_bot_py_plugins.gen_svr.user_svr import *
from none_bot_py_plugins.gen_svr.report_gen import *


class CreateManagerGen(GenSvrBase):

    def __init__(self, recv_id, r_gen_name):
        super(CreateManagerGen, self).__init__(recv_id)
        self.__run_map = {}
        self.__cast_map = {
            "create": lambda msg, state: self.task_create_svr(msg, state)
        }
        self.__report_gen = r_gen_name

    def task_create_svr(self, svr_name, state):
        asyncio.create_task(self.create_svr(svr_name, state))
        return "ok", state

    async def create_svr(self, svr_name, state):
        if svr_name in self.__run_map:
            return "ok", state
        report_name = await self.call(self.__report_gen, ("create", svr_name))
        print(" create report finish ")
        name = create_svr_name(svr_name)
        print(" start create user svr ")
        self.__run_map[name] = UserSvr(name, report_name)
        await self.__run_map[name].task_start()
        print(" create user svr finish ")
        return "ok", state

    def handle_cast(self, from_id, msg, state):
        match, args = msg
        if match in self.__cast_map:
            return self.__cast_map[match](args, state)
        return "ok", state

    def handle_info(self, msg, state):
        return "ok", state

    def handle_call(self, from_id, msg, state):
        print("time: ", time_stamp(), "from id", from_id, "get call msg: ", msg)
        return "ok", "ok, received!", state

    def handle_stop(self, result, state):
        pass

    def handle_error(self, msg, state):
        return "ok", state

    def _init_(self, *args):
        print("create gen start")
        return []


def create_svr_name(name: str):
    return "user_" + name


def create_gen_start(report_gen_name):
    create_gen_name = "create_gen"
    gen_manager = CreateManagerGen(create_gen_name, report_gen_name)
    gen_manager.task_start([]),
    return create_gen_name, gen_manager

